package com.chinaoct.siku.application;

import com.alibaba.fastjson.JSONObject;
import com.chinaoct.siku.vo.TokenInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.UUID;
@Slf4j
@Component
public class TokenInfoApplication {

    @Autowired
    private  GuavaLocalCache localCache;


    public boolean checkActive(String token,String username){
        String info=localCache.get(token);
        if(StringUtils.isEmpty(info)){
            return false;
        }else{
            TokenInfo tokenInfo=JSONObject.parseObject(info,TokenInfo.class);
            if(null!=tokenInfo){
                if(username.equals(tokenInfo.getUsername())){
                    return true;
                }
            }
            return false;
        }
    }

    public String checkToken(String token){
        String info=localCache.get(token);
        if(StringUtils.isEmpty(info)){
            return null;
        }
        TokenInfo tokenInfo=JSONObject.parseObject(info,TokenInfo.class);
        if(null!=tokenInfo){
            return  tokenInfo.getUsername();
        }
        return null;
    }

    public void destroyToken(String token) {
        localCache.delete(token);
    }

    public TokenInfo createTokenByBim(String username){
        if(StringUtils.isEmpty(username)){
            return  null;
        }
        UUID uuid = UUID.randomUUID();
        String token=uuid.toString();
        TokenInfo tokenInfo=new TokenInfo(token,username);

        localCache.put(token, JSONObject.toJSONString(tokenInfo));
        return  tokenInfo;

    }

}
